package com.supor.aiot.md_msg.ui;

import android.os.Bundle;
import android.text.Layout;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMEnhanceFragment;
import com.supor.aiot.common.entity.DeviceInfo;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.utils.NotNullUtils;
import com.supor.aiot.md_msg.R;
import com.supor.aiot.md_msg.adapter.MsgListAdapter;
import com.supor.aiot.md_msg.databinding.FragmentServiceNotificBinding;
import com.supor.aiot.md_msg.entity.AddrJsonBean;
import com.supor.aiot.md_msg.entity.MsgCenterListResultBean;
import com.supor.aiot.md_msg.model.MsgCenterModel;

/**
 * @author: zook
 * @date: 2021/10/14
 */
public class ServiceNotificFragment extends BaseMVVMEnhanceFragment<MsgCenterModel, FragmentServiceNotificBinding> implements View.OnClickListener, OnItemChildClickListener {

    private MsgListAdapter msgListAdapter;
    private int currentListPage;
    private AppBasicDialog checkDialog;

    public static ServiceNotificFragment newInstance() {
        ServiceNotificFragment fragment = new ServiceNotificFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initData() {
        super.initData();
        bindingView.llMsgCleanRead.setOnClickListener(this);
        bindingView.llMsgDelAll.setOnClickListener(this);

        viewModel.getSystemMsgListResult().observe(this, new Observer<Result<MsgCenterListResultBean>>() {
            @Override
            public void onChanged(Result<MsgCenterListResultBean> msgCenterListBeanResult) {
                closeLoading();
                if (currentListPage == 1) {
                    msgListAdapter.getData().clear();
                }
                msgListAdapter.addData(msgCenterListBeanResult.getData().getRows());

                bindingView.smartRefreshLayout.finishLoadMore();
                if (msgCenterListBeanResult.getData().getPage() >= msgCenterListBeanResult.getData().getAllpages()) {
                    bindingView.smartRefreshLayout.setEnableLoadMore(false);
                }
                if (currentListPage == 1 && (null == msgCenterListBeanResult.getData() || msgCenterListBeanResult.getData().getTotal() == 0)) {
                    msgListAdapter.setEmptyView(R.layout.layout_msg_empty);
                }
            }
        });
        viewModel.getCleanMsgResult().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> stringResult) {
                if (stringResult instanceof Result.Success) {
                    if (null != GlobalDataCache.userInfo) {
                        viewModel.getSystemMsgList(GlobalDataCache.userInfo.getBossUserId(),
                                currentListPage = 1,
                                bindDestoryAutoDispose()
                        );
                    }
                }
            }
        });

        viewModel.getDelAllMsgResult().observe(this, new Observer<Result<String>>() {
            @Override
            public void onChanged(Result<String> stringResult) {
                if (stringResult instanceof Result.Success) {
                    if (null != GlobalDataCache.userInfo) {
                        viewModel.getSystemMsgList(GlobalDataCache.userInfo.getBossUserId(),
                                currentListPage = 1,
                                bindDestoryAutoDispose()
                        );
                    }
                }
            }
        });

        msgListAdapter = new MsgListAdapter();
        bindingView.rvContent.setLayoutManager(new LinearLayoutManager(getContext()));
        bindingView.rvContent.setAdapter(msgListAdapter);
//        msgListAdapter.setEmptyView(R.layout.layout_msg_skele);

        bindingView.smartRefreshLayout.setEnableRefresh(false);
        bindingView.smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getSystemMsgList(GlobalDataCache.userInfo.getBossUserId(),
                        ++currentListPage,
                        bindDestoryAutoDispose()
                );
            }
        });

//        msgListAdapter.setOnItemClickListener(this);
        msgListAdapter.setOnItemChildClickListener(this);
//        viewModel.getMsgReadResult().observe(this, new Observer<Result<String>>() {
//            @Override
//            public void onChanged(Result<String> stringResult) {
//
//            }
//        });
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (null != GlobalDataCache.userInfo) {
            showLoading();
            viewModel.getSystemMsgList(GlobalDataCache.userInfo.getBossUserId(),
                    ++currentListPage,
                    bindDestoryAutoDispose()
            );
        }
    }

    @Override
    public void onClick(View view) {
        if (view == bindingView.llMsgCleanRead) {
            viewModel.cleanAllRead(bindDestoryAutoDispose());
        } else if (view == bindingView.llMsgDelAll) {
            showDeleteDialog("提示", "确定要清空消息列表？");
        }
    }

//    @Override
//    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//        if (msgListAdapter.getData().size() > position) {
//            viewModel.readMsg(String.valueOf(msgListAdapter.getData().get(position).getMessageId()), bindDestoryAutoDispose());
//            msgListAdapter.getData().get(position).setIsRead("1");
//
//            if (null != msgListAdapter.getData().get(position).getAddrJson()) {
//                AddrJsonBean addrJsonBean = msgListAdapter.getData().get(position).getAddrJson();
//                if ("DEVICEBIND".equals(addrJsonBean.getType()) || "COOKINGFINISH".equals(addrJsonBean.getType())) {
//                    devicePage(addrJsonBean.getDid());
//                }
//            }
//        }
//    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (msgListAdapter.getData().size() > position) {
            if (R.id.ll_content == view.getId()) {
                if (msgListAdapter.getData().size() > position) {
                    viewModel.readMsg(String.valueOf(msgListAdapter.getData().get(position).getAutoId()), bindDestoryAutoDispose());
                    msgListAdapter.getData().get(position).setIsRead("1");
                    View unreadView = msgListAdapter.getViewByPosition(position, R.id.view_unread);
                    if (null != unreadView) {
                        unreadView.setVisibility(View.GONE);
                    }
                    if (null != msgListAdapter.getData().get(position).getAddrJson()) {
                        AddrJsonBean addrJsonBean = msgListAdapter.getData().get(position).getAddrJson();
                        if (addrJsonBean.getIsJump() == 1) {
                            if ("DEVICEBIND".equals(addrJsonBean.getType()) || "COOKINGFINISH".equals(addrJsonBean.getType())) {
                                devicePage(addrJsonBean);
                            } else if ("NEWRECIPE".equals(addrJsonBean.getType())) {
//                                {"typeId":"2021110313530510033","type":"NEWRECIPE","isJump":1}//食谱上新提醒
//                                详情掉用（取typeId）
                                AppAgent.startRecipePage(addrJsonBean.getTypeId(), addrJsonBean.getProductModel());
                            }
                        }
                    }
                }
            } else if (R.id.ll_right_del == view.getId()) {
                viewModel.delMsg(String.valueOf(msgListAdapter.getData().get(position).getAutoId()),
                        bindDestoryAutoDispose());
                msgListAdapter.removeAt(position);
            }
        }
    }

    private void devicePage(AddrJsonBean addrJsonBean) {
        if (GlobalDataCache.deviceTree != null && GlobalDataCache.deviceTree.device != null) {
            // 有匹配的设备，跳转设备详情页
            for (DeviceInfo info : GlobalDataCache.deviceTree.device) {
                if (info.did.equalsIgnoreCase(NotNullUtils.getNotNullValue(addrJsonBean.getDid()))
                        || info.mac.equalsIgnoreCase(NotNullUtils.getNotNullValue(addrJsonBean.getMac()))) {
                    JSONObject jo = JSONObject.parseObject(GsonUtil.getInstance().toJson(info));
                    jo.put("deviceData", jo.getString("originalData"));
                    jo.remove("originalData");
                    if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(info.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_C,
                                jo.toJSONString());
                    } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(info.type)) {
                        AppAgent.startDevicePage(Constants.App.TINY_DEVICE_OVEN,
                                jo.toJSONString());
                    }
                    return;
                }
            }
        }
    }

    private void showDeleteDialog(String title, String message) {
        if (checkDialog != null && checkDialog.isShowing()) {
            checkDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(getActivity(), false);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            viewModel.delAllMsg(bindDestoryAutoDispose());
            dialog.cancel();
        });
        checkDialog = builder.create();
        checkDialog.setCancelable(false);
        checkDialog.show();
    }
}
